﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Reflection;

public partial class consultas_Default : System.Web.UI.Page
{

    DataTable result = new DataTable();
    private int[] widestData;

    private void InitArrayWithZeros()
    {
        for(int i =0;i<widestData.Length;i++)   widestData[i] = 0;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        widestData= new int[GridView1.Columns.Count];
        InitArrayWithZeros();

        sqlds_vwMonitoreoTickets.SelectCommand = Session["SelectCommand"].ToString();
        sqlds_vwMonitoreoTickets.DataBind();
        sqlds_vwMonitoreoTickets.Selecting += sqlds_vwMonitoreoTickets_Selecting;


        if (GridView1.Rows.Count == 0)
        {
            lblError.Text = "No se encontraron resultados.";
            lblError.Visible = true;
            pnlExportar.Visible = false;
        }
    
    }
    

    protected void sqlds_vwMonitoreoTickets_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
        e.Command.CommandTimeout = 180;
    }

    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        DataView dv = (DataView)sqlds_vwMonitoreoTickets.Select(DataSourceSelectArguments.Empty);

        result = dv.ToTable();
        ExcelExporter excelExporter = new ExcelExporter(this);

        string fechaInicio = null;
        string fechaFin = null;
        if (Session["Fecha_ini"] != null)
            fechaInicio = Session["Fecha_ini"].ToString();

        if (Session["Fecha_fin"] != null)
            fechaFin = Session["Fecha_fin"].ToString();




        if (fechaFin != null && fechaInicio != null)
        {
            excelExporter.AddModifier("fecha", this.ConvertirFechaCorta);
            excelExporter.AddModifier("HoraEmision", this.ObtenerFormatoHoraLargo);
            excelExporter.AddModifier("HoraAsignacion", this.ObtenerFormatoHoraLargo);
            excelExporter.AddModifier("HoraInicioAtencion", this.ObtenerFormatoHoraLargo);
            excelExporter.AddModifier("HoraFinAtencion", this.ObtenerFormatoHoraLargo);
            excelExporter.Export(result, "Monitoreo_Tickets_" + fechaInicio + "-" + fechaFin);
        }

    }

    public object ConvertirFechaCorta(object value)
    {
        DateTime fecha;
        if (value != null && DateTime.TryParse(value.ToString(), out fecha))
            return fecha.ToShortDateString();
        return value;
    }
    public object ObtenerFormatoHoraLargo(object value)
    {
        DateTime fecha;
        if (value != null && DateTime.TryParse(value.ToString(), out fecha))
            return String.Format("{0:HH:mm:ss}", fecha);
        return value;
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        System.Data.DataRowView drv;
        drv = (System.Data.DataRowView)e.Row.DataItem;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (drv != null)
            {
                for (int i = 0; i < widestData.Length; i++)
                {
                    string currentValue= drv[i].ToString();

                    if (currentValue.Length>widestData[i])
                    {
                        widestData[i] = currentValue.Length;
                        GridView1.Columns[i].ItemStyle.Width = widestData[i] ;
                        GridView1.Columns[i].ItemStyle.Wrap = false;
                    }
                }
            }
        }
    }
}












/*
 *
DataTable dt = result;

string attachment = "attachment; filename=Employee.xls";

Response.ClearContent();

Response.AddHeader("content-disposition", attachment);

Response.ContentType = "application/vnd.ms-excel";

string tab = "";

foreach (DataColumn dc in dt.Columns)
{

    Response.Write(tab + dc.ColumnName);

    tab = "\t";

}

Response.Write("\n");



int i;

foreach (DataRow dr in dt.Rows)
{

    tab = "";

    for (i = 0; i < dt.Columns.Count; i++)
    {

        Response.Write(tab + dr[i].ToString());

        tab = "\t";

    }

    Response.Write("\n");

}

Response.End();



*/


/*  PrepareGridViewForExport(GridView1);

  ExportGridView();
  */
/*
        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);
        HtmlTextWriter htw = new HtmlTextWriter(sw);

        Page pagina = new Page();
        HtmlForm form = new HtmlForm();



        this.GridView1.EnableViewState = false;
        pagina.EnableEventValidation = false;
        pagina.Controls.Add(form);
        form.Controls.Add(this.GridView1);
        pagina.RenderControl(htw);

        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("Content-Disposition", "attachment;filename=data.xls");
        Response.Charset = "UTF-8";
        Response.ContentEncoding = Encoding.Default;
        Response.Write(sb.ToString());
        Response.End();

        */

/*StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htw = new HtmlTextWriter(sw);

Page page = new Page();
HtmlForm form = new HtmlForm();

GridView1.EnableViewState = false;

// Deshabilitar la validación de eventos, sólo asp.net 2
page.EnableEventValidation = false;

// Realiza las inicializaciones de la instancia de la clase Page que requieran los diseñadores RAD.
page.DesignerInitialize();

page.Controls.Add(form);
form.Controls.Add(this.GridView1);

page.RenderControl(htw);

Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=data.xls");
Response.Charset = "UTF-8";
Response.ContentEncoding = Encoding.Default;
Response.Write(sb.ToString());
Response.End();*/





//public override void VerifyRenderingInServerForm(Control control)
//{


//    return;
//}